//定义全局变量
var token = selectByKey("like_token");
var dirpath = "../../statics/images/trolley/";
var packingFee, shortFreight, freight;
var orNext, status = 0,
	couponId = '',
	isUsecoupon = '',
	deliverId = '';
var order_type, moneyNeedToPay;

function s(select) {
	return document.querySelector(select);
}

function fetch(key) {
	return localStorage.getItem(key);
}

function isEmptyObject(obj) {
	var sum = 0;
	for(var t in obj) {
		sum++;
	}
	if(sum == 0) {
		return false;
	} else {
		return true;
	}
}

function reEnter() {
	s('.info').style.display = 'block';
	s('.info').style.width = '75%';
	s('.info').style.left = '12.5%';
	s('.info p').innerHTML = '登录状态已过期，请重新登录';
	setTimeout(function() {
		window.location.href = '../personal/enter.html';
	}, 1500);
}

function changeSelect(dom, m, addrLists, cb) {
	var srcNameArr = dom.children[m].src.split("/");
	var srcName = srcNameArr[srcNameArr.length - 1];
	if(srcName == 'Oval.png') {
		for(var j = 0; j < addrLists.length; j++) {
			addrLists[j].children[m].src = dirpath + 'Oval.png';
		}
		dom.children[m].src = dirpath + 'iconfont-gou.png';
		if(cb) {
			cb();
		}
	}
}
//购物清单模板
function jshtml(data, scriptdom) {
	var mainmax = document.getElementById('mainlist');
	var html = "";
	var totleNum = 0;
	for(var k in data) {
		var htmlm = scriptdom.innerHTML;
		htmlm = htmlm.replace(/\{\{src\}\}/, data[k].good_img);
		htmlm = htmlm.replace(/\{\{num\}\}/, data[k].good_num);
		htmlm = htmlm.replace(/\{\{h3\}\}/g, data[k].good_name);
		htmlm = htmlm.replace(/\{\{price\}\}/, data[k].good_price);
		htmlm = htmlm.replace(/\{\{id\}\}/, data[k].good_id);
		html += htmlm;
		totleNum += parseInt(data[k].good_num);
	}
	mainmax.innerHTML = html;
	return totleNum;
}

function addPrice(comPrice, freightTemp, packingFeeTemp, couponPriceTemp) {
	s('#freight').innerHTML = freightTemp;
	s('#packingFee').innerHTML = packingFeeTemp;
	s('#finalPrice').innerHTML = parseFloat(comPrice) + parseFloat(packingFeeTemp) + parseFloat(freightTemp);
	s('#couponPrice').innerHTML = couponPriceTemp;
	s('#needPay').innerHTML = s('#finalPrice').innerHTML - couponPriceTemp;
}
//添加地址模板
function addAddrFn(data, scriptdom) {
	var mainmax = document.getElementById('main');
	var html = mainmax.innerHTML;
	for(var k in data) {
		var htmlm = scriptdom.innerHTML;
		if(k == 0) {
			htmlm = htmlm.replace(/\{\{src\}\}/, dirpath + "iconfont-gou.png");
		} else {
			htmlm = htmlm.replace(/\{\{src\}\}/, dirpath + "Oval.png");
		}
		console.log(data[k].full_name)
		htmlm = htmlm.replace(/\{\{areaid\}\}/, data[k].id);
		htmlm = htmlm.replace(/\{\{id\}\}/, data[k].area_id);
		htmlm = htmlm.replace(/\{\{name\}\}/, data[k].name);
		htmlm = htmlm.replace(/\{\{phone\}\}/g, data[k].phone);
		htmlm = htmlm.replace(/\{\{area\}\}/, data[k].full_name);
		htmlm = htmlm.replace(/\{\{address\}\}/, data[k].address);
		html += htmlm;
	}
	mainmax.innerHTML = html;
	addressOperate(data[0]);
}
//西安自营店样式
function addrStyle(areaId) {
	s('#adressc').style.padding = '10px 15px';
	s('.addFirst').style.display = 'none';
	var title = s('.p1');
	var place = s('.p2');
	title.style.fontSize = "16px";
	title.style.fontWeight = "bold";
	title.style.lineHeight = "18px";
	place.style.lineHeight = "19px";
	place.style.padding = '10px 0';
	if(areaId == 311) {
		title.innerHTML = "西安自提";
		place.innerHTML = '西安市含光北路新兴际华大厦下沉式广场03号/02985416061(西安自提点地址及电话)';
	} else if(areaId == 383) {
		title.innerHTML = "杭州自提";
		place.innerHTML = '杭州市滨江区聚光科技物联网产业化大楼c2-101/0571-87552153(杭州自提点地址及电话)';
	} else if(areaId == 223) {
		title.innerHTML = "常州自提";
		place.innerHTML = '江苏省常州市天宁区青山湾花园12-1/0519-85338389(常州自提点地址及电话)';
	}
}
//请求是否支持配送
function orSupportDeliver(arrObj, sqlId) {
	console.log(arrObj)
	$.ajax({
		url: pathName + "/api/v1/member/cart/122/updateAddress",
		type: "POST",
		dataType: "json",
		headers: {
			"Accept": "application/json",
			"Authorization": "Bearer " + token
		},
		data: {
			"shop_goods": arrObj,
			"area_id": sqlId,
			"couponId": couponId
		},
		success: function(data) {
			console.log(data);
			s('.mask').style.display = "none";
			var orSupport = data.status;
			if(orSupport == undefined || orSupport == true) {
				orNext = true;
			} else {
				orNext = false;
			}
			orSubmit();
			var residualNum = data.member_balance || 0;
			if(orNext) {
				s('#freight').innerHTML = data.freight || 0;
				moneyNeedToPay = data.total - residualNum;
				s('#needPay').innerHTML = moneyNeedToPay;
				s('#couponPrice').innerHTML = data.couponPrice == 0 ? 0 : ('-' + data.couponPrice);
				s('#finalPrice').innerHTML = (parseFloat(data.total) + parseFloat(data.couponPrice)).toFixed(2);
			}
		},
		error: function() {
			if(!token) {
				reEnter();
			}
		}
	})
}

function addressOperate(addressTemp) {
	var choose = s('#address a');
	var addrLists = document.querySelectorAll('.addrList');
	var foot = s('footer');
	var sqlId = addressTemp.area_id;
	var addrTemp = addressTemp;
	console.log(addressTemp);
	Tap(choose, function() {
		s('.contenter').style.display = 'none';
		s('#main').style.display = 'block';
		status = 1;
		orSubmit();
	})
	for(var i = 0; i < addrLists.length; i++) {
		Tap(addrLists[i], function(e, dom) {
			changeSelect(dom, 0, addrLists, function() {
				addrTemp.name = dom.children[1].children[0].innerHTML;
				addrTemp.phone = dom.children[1].children[1].innerHTML;
				addrTemp.full_name = dom.children[2].children[0].innerHTML;
				addrTemp.address = dom.children[2].children[1].innerHTML;
				addrTemp.area_id = dom.getAttribute('data-id');
				sqlId = dom.getAttribute('data-id');
				deliverId = dom.getAttribute('data-area_id');
			});
		});
	}
	Tap(foot, function() {
		if(status == 1) {
			status = 0;
			var str = fetch('str');
			var arrObj = JSON.parse(str);
			s('.contenter').style.display = 'block';
			s('#main').style.display = 'none';
			showAddress(addrTemp);
			console.log(arrObj, sqlId);
			orSupportDeliver(arrObj, sqlId);
			s('.mask').style.display = "block";
		}
	})
}
//显示地址内容
function showAddress(oneAddress) {
	s('.p1 span').innerHTML = oneAddress.name;
	s('.p1 i').innerHTML = oneAddress.phone;
	s('.p2 s').innerHTML = oneAddress.full_name;
	s('.p2 label').innerHTML = oneAddress.address;
}
//添加优惠券模板
function couponMode(data, payMoney) {
	var html = "";
	//var payMoney = needPay.innerHTML;
	var num = 0;
	var arr = [];
	var nowDate = new Date().getTime();
	for(var i = 0; i < data.length; i++) {
		var beginTime = data[i].begin_time.replace(/\-/g, "/");
		beginTime = Date.parse(new Date(beginTime));
		var endTime = data[i].end_time.replace(/\-/g, "/");
		endTime = Date.parse(new Date(endTime));
		if(parseFloat(data[i].limit) < parseFloat(payMoney) && nowDate >= beginTime && nowDate <= endTime && parseInt(data[i].pivot.is_used) == 0) {
			num++;
			var temp = '<p data-coupon_id="' + data[i].id + '" data-temp_couponPrice="' + data[i].price + '"><span>活动商品购满' + data[i].limit + '元，减' + data[i].price + '元现金</span><img src="' + dirpath + 'Oval.png"></p>';
			html += temp;
		}
	}
	html += '<p><span>不使用优惠</span><img src="' + dirpath + 'iconfont-gou.png" alt=""/></p>';
	s('.youhui_content').innerHTML = html;
	var heightM = s('.youhui').offsetHeight;
	s('.youhui').style.height = 0 + 'px';
	s('.youhui').style.opacity = 1;
	s('.youhui').style.display = 'none';
	arr.push(heightM);
	arr.push(num);
	return arr;
}
//获取优惠券列表
function getCouponList() {
	$.ajax({
		url: pathName + "/api/v1/member/myCoupons",
		type: "get",
		headers: {
			"Accept": "application/json",
			"Authorization": "Bearer " + token
		},
		success: function(res) {
			// console.log(res);
			var pay = s('#needPay').innerHTML;
			var arrTemp = couponMode(res.data, pay);
			var H = arrTemp[0];
			//如果没有优惠券不能点
			if(arrTemp[1] == 0 || order_type == 1) {
				var orClick = false;
				s('.mp2 img').style.display = "none";
			} else {
				var orClick = true;
			}
			couponOperate(H, orClick);
		}
	})
}
//优惠券操作
function couponOperate(H, orClick) {
	var couponNode = s('main .mp2');
	var couponLists = document.querySelectorAll('.youhui_content p');
	var closeNode = s('#close');
	Tap(couponNode, function() {
		if(orClick) {
			s('.youhui').style.display = 'block';
			s('.youhui_mask').style.display = 'block';
			setTimeout(function() {
				s('.youhui').style.height = H + 'px';
			}, 50);
		}
	});

	function close() {
		setTimeout(function() {
			s('.youhui').style.height = 0 + 'px';
			s('.youhui_mask').style.display = 'none';
		}, 100);
	}
	for(var i = 0; i < couponLists.length - 1; i++) {
		Tap(couponLists[i], function(e, dom) {
			couponId = dom.getAttribute('data-coupon_id');
			couponPrice = dom.getAttribute('data-temp_couponprice');
			s('#couponPrice').innerHTML = '-' + couponPrice;
			s('#needPay').innerHTML = moneyNeedToPay - couponPrice;
			changeSelect(dom, 1, couponLists);
			s('.mp2 s').innerHTML = dom.children[0].innerHTML;
			close();
			isUsecoupon = "enabled";
		});
	}
	Tap(couponLists[couponLists.length - 1], function(e, dom) {
		changeSelect(dom, 1, couponLists);
		s('#couponPrice').innerHTML = 0;
		s('#needPay').innerHTML = moneyNeedToPay;
		couponId = '';
		s('.mp2 s').innerHTML = '';
		close();
		isUsecoupon = "";
	});
	Tap(closeNode, function() {
		close();
	});
}

function orSubmit() {
	if(status == 0) {
		s('footer a').innerHTML = '提交订单';
		if(orNext) {
			s('footer').style.background = 'black';
			s('footer p').style.display = 'none';
		} else {
			s('footer').style.background = 'lightGray';
			s('footer p').style.display = 'block';
		}
	} else {
		s('footer').style.background = 'black';
		s('footer a').innerHTML = '确认';
		s('footer p').style.display = 'none';
	}
}

function goBack() {
	var backNode = s('header a');
	Tap(backNode, function() {
		if(status == 1) {
			s('.contenter').style.display = 'block';
			s('#main').style.display = 'none';
			status = 0;
		} else {
			window.history.back();
		}
	})
}
//提交订单
function submit() {
	var submitNode = s('footer');
	Tap(submitNode, function() {
		console.log("click", status, orNext);
		if($("#remark").val()) {
			s('footer p').style.display = 'none';
			if(status == 0 && orNext == true) {
				var arrstr = fetch("str");
				var arrObj = JSON.parse(arrstr);
				console.log(arrObj)
				var orderN = fetch("orderId");
				var cartIdsStr = fetch("cartIds");
				var cartIds = JSON.parse(cartIdsStr);
				var remark = s('#remark').value;
				//ajax请求提交订单
				console.log(deliverId)
				$.ajax({
					url: pathName + "/api/v1/member/cart/" + cartIds[0] + "/order",
					type: "POST",
					dataType: "json",
					headers: {
						"Accept": "application/json",
						"Authorization": "Bearer " + token,
					},
					data: {
						"shop_goods": arrObj,
						"address_id": deliverId,
						"order_no": orderN,
						"couponId": couponId,
						"remark": remark,
						"isUseCoupon": isUsecoupon,
						"order_type": order_type
					},
					success: function(data) {
						console.log(data);
						localStorage.setItem("orderId", data.order_no);
						localStorage.setItem("deliverId", deliverId);
						window.location.href = "payorder.html";
					},
					error: function(data) {
						if(!token) {
							reEnter();
						}
						var response = data.responseText;
						response = JSON.parse(response);
						s(".info").style.display = "block";
						if(response.code == 20020) {
							setTimeout(function() {
								window.location.href = "orders.html#waitPay";
							}, 1500);
						} else {
							setTimeout(function() {
								window.location.href = "../trolley.html";
							}, 1500);
						}
					}
				});
			}

		} else {
			s('footer').style.background = 'black';
			s('footer a').innerHTML = '提交订单';
			s('footer p').style.display = 'block';
		}

	});
}

window.onload = function() {
	goBack();
	//先获取购物车传过来的值
	var cartIds = JSON.parse(fetch("cartIds"));
	$.ajax({
		url: pathName + "/api/v1/member/cart/" + cartIds[0] + "/order/result",
		type: "POST",
		dataType: "json",
		headers: {
			"Accept": "application/json",
			"Authorization": "Bearer " + token
		},
		data: {
			"cartIds": cartIds
		},
		success: function(res) {
			console.log(res);
			s('.mask').style.display = 'none';
			//购物清单部分
			s('#totleNum').innerHTML = jshtml(res.buyGoods, s("#listMode"));
			packingFee = parseFloat(res.packingFee) || 0;
			shortFreight = parseFloat(res.shortFreight) || 0;
			freight = parseFloat(res.freight) || 0;
			packingFee = packingFee + shortFreight; //打包费
			var comPrice = parseFloat(res.comPrice) || 0;
			var residual = res.member_balance || 0;
			s('#freight').innerHTML = freight;
			s('#packingFee').innerHTML = packingFee;
			s('#finalPrice').innerHTML = (parseFloat(comPrice) + parseFloat(packingFee) + parseFloat(freight)).toFixed(2);
			moneyNeedToPay = (parseFloat(comPrice) + parseFloat(packingFee) + parseFloat(freight) - residual).toFixed(2);
			s('#needPay').innerHTML = moneyNeedToPay;
			//地址部分
			var orEmpty = isEmptyObject(res.addressDetail);
			order_type = res.order_type;
			if(orEmpty) {
				deliverId = res.addressDetail[0].id;
				submit();
				addAddrFn(res.addressDetail, s('#addrMod'));
				showAddress(res.addressDetail[0]);
				s('#address').style.display = 'block';
			} else {
				if(order_type != 1) {
					s('#adressc').style.display = 'none';
					s('.addFirst').style.display = 'block';
				} else {
					var regionId = Math.floor(res.region_id);
					switch(regionId) {
						case 311:
							deliverId = '1';
							break;
						case 383:
							deliverId = '2';
							break;
						case 223:
							deliverId = '3';
							break;
					}
					addrStyle(regionId);
					submit();
				}

			}
			//优惠券部分
			getCouponList();
			//提交订单
			orNext = res.status;
			orSubmit();
		},
		error: function(res) {
			if(!token) {
				reEnter();
			}
			var resText = JSON.parse(res.responseText);
			if(resText.code == 20020) {
				s(".info").style.display = "block";
				setTimeout(function() {
					window.location.href = "orders.html#waitPay";
				}, 1500);
			}
		}
	})
}